package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego/validation"
	"h1/contant"
	"h1/models"
	"h1/utils"
	"h1/vo"
	"regexp"
	"time"
)

// @Title 用户注册
// @router /register [post]
func (this *UserLoginController) Register() {

	valid := validation.Validation{}
	result := DataResponse{}
	userForm := vo.RegisterFormParm{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, &userForm)

	//1.邮箱验证
	valid.Match(userForm.Email, regexp.MustCompile(contant.RexEmail), "email").Message("邮箱的格式不正确，请检查！")

	// 2.手机号
	valid.Match(userForm.Phone, regexp.MustCompile(contant.RexPhone), "phone").Message("手机号格式不正确，请检查！")

	//-------------用户信息获取-----------------------------------------
	//Users := this.GetUserByToken()

	//-------------参数验证-----------------------------------------
	if str := this.VerifyParams(valid, userForm); str != "" {
		this.Data["json"] = Response(1, "", str)
		this.ServeJSON()
		return
	}

	// --------------------------具体业务--------------------------------------------
	userModel := models.User{}
	if u, err := userModel.GetUserByEmail(userForm.Email); err == nil && u.Id != 0 {
		this.Data["json"] = Response(1, "", "帐号已经存在或无效!")
		this.ServeJSON()
		return
	}
	if userForm.Password != userForm.Rpassword {
		this.Data["json"] = Response(1, "", "密码不一致，请检查!")
		this.ServeJSON()
		return
	}
	userModel.Name = userForm.Name
	userModel.Password = utils.EnMd5(userForm.Password)
	userModel.Phone = userForm.Phone
	userModel.Department = userForm.Department
	userModel.Email = userForm.Email
	userModel.RegisterType = "0"
	userModel.CreateName = userForm.Name
	userModel.UpdateName = userForm.Name
	if err := userModel.Insert(); err != nil {
		result = Response(1, "", utils.FormatErrorToString(err))
	} else {
		models.InserUserLoggerInfo(userModel, "注册用户", "注册新用户：'"+userForm.Email+"'")
		result = Response(0, models.UserJson(&userModel), "注册成功")
	}
	this.Data["json"] = result
	this.ServeJSON()
}

// @Title 用户登录
// @router /login [post]
func (this *UserLoginController) Login() {

	valid := validation.Validation{}
	result := DataResponseToken{}
	LoginForm := vo.LoginFormParm{}
	_ = json.Unmarshal(this.Ctx.Input.RequestBody, &LoginForm)

	//1.邮箱验证
	valid.Match(LoginForm.Email, regexp.MustCompile(contant.RexEmail), "email").Message("邮箱的格式不正确，请检查！")

	//-------------参数验证-----------------------------------------
	if str := this.VerifyParams(valid, LoginForm); str != "" {
		this.Data["json"] = Response(1, "", str)
		this.ServeJSON()
		return
	}

	//信息处理
	userMod := &models.User{Email: LoginForm.Email, Password: utils.EnMd5(LoginForm.Password)}

	//1.账号是否存在判断
	_, err1 := userMod.LoginUserByEmail(LoginForm.Email)
	if err1 != nil {
		this.Data["json"] = ResponseToken(1, "", "账号不存在或无效", "")
		this.ServeJSON()
		return
	}

	//2.判断账号与密码是否正确
	uId, err := userMod.Read("Email", "Password")
	timestamp := time.Now().Unix()
	if err == nil {
		tokenStr, err := this.GenToken(uId, timestamp)
		if err != nil {
			this.Data["json"] = ResponseToken(1, "", "获取token存在问题", "")
			this.ServeJSON()
			return
		}
		//更新登陆时间
		UlM := models.User{}
		UlM.Id = uId
		UlM.Timestamp = timestamp
		if reErr := UlM.Update("timestamp"); reErr != nil {
			this.Data["json"] = ResponseToken(1, "", "更新时间戳失败", "")
			this.ServeJSON()
			return
		}
		// 转化为json结构
		res := models.UserJson(userMod)
		result = ResponseToken(0, res, "登录成功", tokenStr)
	} else {
		result = ResponseToken(1, "", "邮箱输入错误或者密码输入错误", "")
	}
	this.Data["json"] = result
	this.ServeJSON()
}
